/**
 * 教研老师查看报名自己某个课题的学生，某个课题的报名学生
 * 
 * /jiaoyan/student/list
 */

const Topics= require('../../../models/researchTopics')
const Topic_Student = require('../../../models/researchTopicStudents')
const User_Info = require('../../../models/usersInfo')
const utils = require('../../../utils/index')
const $ = require('../../../utils/common')

const get_list = async function (req, res) {
    try {
        Topic_Student.belongsTo(User_Info,
            {
                foreignKey: 'student_user_name',
                targetKey: 'user_name'
            })

        // set a relation with years
        if (!req.body.topic_id) {
            $.sendMessage(res, 1015, '参数topic_id不能缺少')
            return
        }

        // 判断该课题是否属于当前用户
        var topic = await Topics.findOne({
            where: {
                id: req.body.topic_id
            }
        })

        if (topic == null) {
            $.sendMessage(res, 1015, '无效id')
            return
        }

        if (req.user_name != topic.dataValues.teacher_user_name) {
            $.sendMessage(res, 1015, '水平越权')
            return
        }

        // 找出报名此课题的学生
        var topic_students = await Topic_Student.findAndCountAll({
            where: {
                topic_id: req.body.topic_id
            },
            attributes:['id', 'student_status'],
            include: [
                {
                    model: User_Info,
                    attributes: ['user_fullname', 'user_sex', 'user_major',
                    'user_phone', 'user_email', 'user_name'
                ],
                }
            ],
            raw:true // 这个属性表示开启原生查询，原生查询支持的功能更多，自定义更强
            // attributes: ['id', 'topic_name', 'topic_resource', 'research_direction', 'student_limit',
            // 'topic_status', 'topic_background', 'current_student', 'confirm_num']
        })

        res.json({
            code: 200,
            message: '获取成功',
            data: topic_students
        })
          
        // 日志
        utils.create_a_log(req, '科研题目管理', '浏览报名学生列表')
    }
    catch(error) {
        $.log('catch error :', error)
        res.json({
            message: "抓到异常",
            error: 'error' + error
        })
        utils.create_a_log(req, '科研题目管理', '浏览报名学生列表', '失败')
    } 
}
    
module.exports = get_list